from flask import render_template, redirect, url_for, flash, session
from . import main
from .. import db
from ..models import Basicinfo, Major
from ..forms import NameForm, EditForm, DeleteForm
from flask_login import login_required, current_user
from ..decorators import admin_required, guest_required  # 需新建decorators.py

# 首页
@main.route('/')
def index():
    studs = Basicinfo.query.all()
    majors = Major.query.all()
    return render_template('index.html', studs=studs, majors=majors)

# 新增学生（管理员权限）
@main.route('/new', methods=['GET', 'POST'])
@admin_required
def new_stud():
    form = NameForm()
    form.major.choices = [(major.id, major.major_name) for major in Major.query.all()]
    if form.validate_on_submit():
        new_stud = Basicinfo(
            id=form.id.data, 
            studentName=form.studentName.data, 
            studentBirth=form.studentBirth.data, 
            isMale=form.isMale.data, 
            major_id=form.major.data
        )
        db.session.add(new_stud)
        db.session.commit()
        flash('学生信息添加成功！')
        return redirect(url_for('main.index'))
    return render_template('new.html', form=form)

# 编辑学生（管理员权限）
@main.route("/edit/<int:id>", methods=["GET", "POST"])
@admin_required
def edit_stud(id):
    form = EditForm()
    stud = Basicinfo.query.get(id)
    form.major.choices = [(major.id, major.major_name) for major in Major.query.all()]
    if form.validate_on_submit():
        stud.id = form.id.data
        stud.studentName = form.studentName.data
        stud.studentBirth = form.studentBirth.data
        stud.isMale = form.isMale.data
        stud.major = Major.query.get(form.major.data)
        db.session.commit()
        flash('学生信息修改成功！')
        return redirect(url_for('main.index'))
    form.id.data = stud.id
    form.studentName.data = stud.studentName
    form.studentBirth.data = stud.studentBirth
    form.isMale.data = stud.isMale
    if stud.major:
        form.major.data = stud.major.id
    return render_template('edit.html', form=form)

# 删除学生（管理员权限）
@main.route("/delete/<int:id>", methods=["GET", "POST"])
@admin_required
def del_stud(id):
    stud = Basicinfo.query.get(id) 
    db.session.delete(stud)
    db.session.commit()
    flash('学生信息删除成功！')
    return redirect(url_for('main.index'))

# 按专业筛选
@main.route("/major/<int:major_id>")   
def filter_by_major(major_id):
    major = Major.query.get_or_404(major_id)
    studs = major.students.all()
    majors = Major.query.all() 
    return render_template('index.html', studs=studs, majors=majors)

# 测试页面（保留原逻辑）
@main.route('/testvariables')
def testvariables():
    from support import Cat, Dog  # 假设support.py在根目录
    aCat = Cat("苏新皓", 2, 10, "baby Cat")
    aDog = Dog("Bad Dog", 2, 10, "Bad Dog")
    aCat.shout()
    aDog.shout()
    return render_template('testvariables.html', aCat=aCat, aDog=aDog)

@main.route('/user',methods=['GET','POST'])     
@guest_required
def user():
    form=NameForm()
    form.major.choices = [(major.id, major.major_name) for major in Major.query.all()]
    if form.validate_on_submit():
        oldname=session.get('studentName')
        newname=form.studentName.data
        session['studentName'] = newname
        if oldname is None:
            flash('您的姓名提交成功！')
        elif oldname != newname:
            flash('您的姓名已经更新成功！')
        else:
            flash('您的姓名未改变！')
        return redirect(url_for('main.user'))
    return render_template('user.html',form=form,studentName=session.get('studentName'))        
 
@main.route('/<username>')
def test2(username):
    return render_template('test2.html',username=username)

@main.route('/hello/<name>')
def hello(name):
    comments=['你好1','你好2','你好3']
    return render_template('user.html',name1=name,comments=comments,form=NameForm())